package com.fulihui.wgj.schedule.job;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.fulihui.common.result.rpc.BaseResult;
import com.fulihui.common.result.rpc.SimpleResult;
import com.fulihui.common.util.RpcResultCheckUtil;
import com.fulihui.wgj.facade.dto.WxSendTemplateLogDTO;
import com.fulihui.wgj.facade.request.template.CalcSendCountRequest;
import com.fulihui.wgj.facade.service.template.SendTemplateLogService;
import com.fulihui.wgj.facade.service.template.SendTemplateMsgService;
import com.fulihui.wgj.schedule.annotation.MutexLock;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 微信模板消息定时发送
 *
 * @author wang_wx
 * @date 2018-07-31
 */
@Component
public class WxTemplateSendMsgJob {

    private static final Logger LOGGER = LoggerFactory.getLogger(WxTemplateSendMsgJob.class);

    @Reference(version = "1.0.0")
    SendTemplateLogService sendTemplateLogService;

    @Reference(version = "1.0.0")
    SendTemplateMsgService sendTemplateMsgService;

    @MutexLock(node = "${job.node.wxTemplateSendMsgJob_execute}")
    @Scheduled(cron = "${job.cron.wxTemplateSendMsgJob_execute}")
    public void execute() {
        LOGGER.info("WxTemplateSendMsgJob start");
        SimpleResult<List<WxSendTemplateLogDTO>> templateLogResult = sendTemplateLogService.querySendLogs4Job();
        LOGGER.info("templateLogResult 4JOB = {}", templateLogResult);
        if (RpcResultCheckUtil.isSuccess(templateLogResult)) {
            List<WxSendTemplateLogDTO> templateLogDTOS = templateLogResult.getData();
            if (CollectionUtils.isEmpty(templateLogDTOS)) {
                LOGGER.info("there is no template send task !");
                return;
            }
            templateLogDTOS.stream().forEach(wxSendTemplateLogDTO -> {
                Date jobTime = wxSendTemplateLogDTO.getJobTime();
                // 定时任务时间到了 进行发送
                if (Objects.nonNull(jobTime) && jobTime.getTime() <= System.currentTimeMillis()) {
                    LOGGER.info("job wxSendTemplateLogDTO = {}", wxSendTemplateLogDTO);
                    String sendCondition = wxSendTemplateLogDTO.getSendCondition();
                    if (StringUtils.isNotBlank(sendCondition)) {
                        CalcSendCountRequest calcSendCountRequest = JSON.parseObject(sendCondition, CalcSendCountRequest.class);
                        calcSendCountRequest.setRecordId(wxSendTemplateLogDTO.getId());
                        BaseResult baseResult = sendTemplateMsgService.sendTemplateMsg4Job(calcSendCountRequest);
                        if (baseResult.isSuccess()) {
                            LOGGER.info("template job recordId = {}执行成功！", wxSendTemplateLogDTO.getId());
                        } else {
                            LOGGER.info("template job recordId = {}执行失败！", wxSendTemplateLogDTO.getId());
                        }
                    }
                }

            });
            LOGGER.info("WxTemplateSendMsgJob end");
        }
    }

}
